//
//  CCViewController.swift
//  TCC_Base
//
//  Created by tucici on 2024/5/25.
//

import UIKit
#if canImport(TCC_String)
import TCC_String
#endif
#if canImport(TCC_Extension)
import TCC_Extension
#endif
#if canImport(TCC_View)
import TCC_View
#endif
#if canImport(TCC_Object)
import TCC_Object
#endif
#if canImport(TCC_Image)
import TCC_Image
#endif
#if canImport(TCC_Const)
import TCC_Const
#endif
#if canImport(TCC_ViewController)
import TCC_ViewController
#endif
@objcMembers open class CCViewController: UIViewController {
    open var backBtn : UIButton?
    open var editCommentView : UIView!
    private var origin_offsetY = 0.0
    open override func viewDidLoad() {
        super.viewDidLoad()
        view.bgHexColor = "#161718"
        initNavigationBar()
        setupNaviBarColor("#161718".color(), "#FFFFFF".color())
        addTap()
        addNotify()
        initData()
    }
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    open override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    open func initUI(){}
    open func initData(){}
    
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    
    open func initNavigationBar(){
        backBtn = UIButton(type: .custom)
        backBtn?.frame = CGRect(x: 0, y: kUIStatusBarHeight + 5, width: 40, height: 34)
        backBtn?.addTarget(self, action: #selector(backBtnAction), for: .touchUpInside)
        backBtn?.setImage(UIImage(named:"返回")?.withRenderingMode(.alwaysTemplate), for: .normal)
        backBtn?.setImage(UIImage(named:"返回")?.withRenderingMode(.alwaysTemplate), for: .disabled)
        
        let backItem = UIBarButtonItem(customView: backBtn!)
        navigationItem.leftBarButtonItem = backItem
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.black, .font:UIFont.systemFont(ofSize: 18)]
    }
    
    open func setupNaviBarColor(_ bgcolor:UIColor, _ titleColor:UIColor){
        backBtn?.tintColor = titleColor
        if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.backgroundColor = bgcolor
            appearance.backgroundImage = UIImage.withColor(bgcolor)
            appearance.shadowColor = .clear///下划线颜色
            appearance.titleTextAttributes = [.foregroundColor:titleColor,.font:UIFont.systemFont(ofSize: 19)]
            navigationController?.navigationBar.setBackgroundImage(UIImage.withColor(bgcolor), for: .default)
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = appearance
            navigationController?.navigationBar.isTranslucent = false
        }else{
            navigationController?.navigationBar.shadowImage = UIImage()
            navigationController?.navigationBar.barTintColor = bgcolor
            navigationController?.navigationBar.titleTextAttributes = [.foregroundColor:titleColor]
            navigationController?.navigationBar.tintColor = titleColor
            navigationController?.navigationBar.isTranslucent = false
            navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        }
    }
    
    ///添加点击手势
    open func addTap(){
        let tap = UITapGestureRecognizer(target: self, action: #selector(actionForTap))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    /// 点击空白处隐藏键盘
    open func actionForTap(){
        view.endEditing(true)
    }
    
    open func backBtnAction(){
        navigationController?.popViewController(animated: true)
    }
    
    open var tableViewStyle : UITableView.Style = .grouped
    @objc open lazy var tableView:UITableView =
    {
        let view = UITableView(frame:.zero, style:tableViewStyle)
        view.separatorStyle = .none
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.tableHeaderView = UIView(frame:CGRect(x: 0, y: 0, width: 0, height: 0.01))
        view.tableFooterView = UIView(frame:CGRect(x: 0, y: 0, width: 0, height: 0.01))
        view.backgroundColor = "#161718".color()
        if #available(iOS 11.0, *) {
            view.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        if #available(iOS 15.0, *) {
            view.sectionHeaderTopPadding = 0
        } else { }
        self.view.addSubview(view)
        return view
    }()
    
    open var autoAddCollectionView : Bool = true
    open var flowLayout = UICollectionViewFlowLayout()
    @objc open lazy var collectionView: UICollectionView =
    {
        let view = UICollectionView(frame:.zero, collectionViewLayout:flowLayout)
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        view.backgroundColor = "#161718".color()
        if #available(iOS 11.0, *) {
            view.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        if autoAddCollectionView{
            self.view.addSubview(view)
        }
        return view
    }()
    
}

// MARK: - 导航栏特殊效果`1`，导航栏圆角
/// 设置导航栏圆角
@objc extension CCViewController{
    open func setNavBarLayer(bgColor:UIColor){
        let bounds = CGRect(x: 0, y: 0, width: kUIScreenWidth, height: kUINavigationBarHeight)
        let r : CGFloat = 12
        let path = UIBezierPath(roundedRect: bounds,
                                byRoundingCorners: [.bottomLeft,.bottomRight],
                                cornerRadii: CGSize(width: r, height: r))
        let layer = CAShapeLayer()
        layer.frame = bounds
        layer.path = path.cgPath
        layer.fillColor = bgColor.cgColor
        navigationController?.navigationBar.backgroundColor = bgColor
        guard let array1 = navigationController?.navigationBar.subviews as? [UIView] else{return}
        guard array1.count > 0 , let array2 = array1[0].subviews as? [UIView] else {return}
        guard array2.count > 0 , let img = array2[0] as? UIImageView else{return}
        img.layer.mask = layer
    }
}



//MARK: - 键盘相关通知
@objc extension CCViewController{
    @objc open func addNotify(){
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(methodKeyboardShow),
                                               name:Notification.Name( UIResponder.keyboardWillChangeFrameNotification.rawValue),
                                               object: nil)
        
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(methodKeyboardHidden),
                                               name: Notification.Name( UIResponder.keyboardWillHideNotification.rawValue),
                                               object: nil)
    }
    
    @objc open func removeNotify(){
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func methodKeyboardShow(_ notify:Notification){
        let userinfo = notify.userInfo
        let value = userinfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
        let time = (userinfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber) .doubleValue
        let keyboard_H = value.cgRectValue.size.height
        var maxY : CGFloat = 0
        
        let firstView = firstResponder(view)
        if firstView == nil || view?.className == "WKContentView"{
            return
        }
        
        editCommentView = firstView?.commonView(view)!
        let rect = firstView!.convert(firstView!.bounds, to: UIApplication.shared.delegate!.window!)
        maxY = rect.maxY
        
        let map = kUIScreenHeight - maxY - keyboard_H
        if map < 0 {
            if editCommentView == view{
                UIView.animate(withDuration: time) {[weak self] in
                    self?.view.transform = CGAffineTransform(translationX: 0, y: map)
                }
            }else if editCommentView.isKind(of: UITableView.self) ||
                        editCommentView.isKind(of: UICollectionView.self) ||
                        editCommentView.isKind(of: UIScrollView.self){
                guard let scrollView = editCommentView as? UIScrollView else{return}
                origin_offsetY = map < 0 ? scrollView.contentOffset.y : origin_offsetY
                UIView.animate(withDuration: time) {
                    scrollView.contentOffset = CGPoint(x: 0, y: scrollView.contentOffset.y - map)
                }
            }
        }
    }
    
    @objc func methodKeyboardHidden(_ notify:Notification){
        let time = (notify.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber) .doubleValue
        if editCommentView == view{
            UIView.animate(withDuration: time) {[weak self] in
                self?.view.transform = .identity
            }
        }else if editCommentView != nil && (editCommentView.isKind(of: UITableView.self) ||
                    editCommentView.isKind(of: UICollectionView.self) ||
                    editCommentView.isKind(of: UIScrollView.self)){
            guard let scrollView = editCommentView as? UIScrollView else{return}
            UIView.animate(withDuration: time) {[weak self] in
                scrollView.contentOffset = CGPoint(x: 0, y: self?.origin_offsetY ?? 0)
            }
        }
    }
}
